package io.renren.modules.telnets.controller;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.modules.common.entity.EducationEntity;
import io.renren.modules.sys.entity.UserBaseInfoEntity;
import io.renren.modules.telnets.dao.TalentsRepertoryDao;
import io.renren.modules.telnets.dao.TelnetEducationBackgroundDao;
import io.renren.modules.telnets.dao.WorkTrackRecordDao;
import io.renren.modules.telnets.entity.TelnetEducationBackgroundEntity;
import io.renren.modules.telnets.entity.WorkTrackRecordEntity;
import io.renren.modules.telnets.entity.dto.TalentsRepertoryEntityDTO;
import io.renren.modules.telnets.service.TelnetEducationBackgroundService;
import io.renren.modules.telnets.service.WorkTrackRecordService;
import io.renren.modules.workjobs.entity.WorkJobEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.telnets.entity.TalentsRepertoryEntity;
import io.renren.modules.telnets.service.TalentsRepertoryService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;


/**
 * 
 *
 * @author nyc
 * @email 2691778746@qq.com
 * @date 2022-04-06 16:04:29
 */
@RestController
@RequestMapping("telnets/talentsrepertory")
public class TalentsRepertoryController {
    @Autowired
    private TalentsRepertoryService talentsRepertoryService;
    @Autowired
    private TalentsRepertoryDao talentsRepertoryDao;
    @Autowired
    private TelnetEducationBackgroundService educationBackgroundServicel;
    @Autowired
    private TelnetEducationBackgroundDao telnetEducationBackgroundDao;
    @Autowired
    private WorkTrackRecordService workTrackRecordService;
    @Autowired
    private WorkTrackRecordDao workTrackRecordDao;


    /*人才信息头像上传问题*/
    @PostMapping("/talents/uploadAdvator")
    public R uploadAdvator(MultipartFile photo, HttpSession session){
        //获取上传的文件的文件名
        String fileName = photo.getOriginalFilename();

        //处理文件重名问题
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + hzName;

        String photoPath = "E:\\useradvator\\telentadvator\\";

        String finalPath = photoPath + File.separator + fileName;
        //实现上传功能
        try {
            photo.transferTo(new File(finalPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok().put("pathUrl",finalPath);
    }

    /*人才信息头像信息读取进行回显*/
    @PostMapping("/reflectTalentAdvator/{talentId}")
    public R reflectUserAdvator(@PathVariable("talentId")String talentId){

        QueryWrapper<TalentsRepertoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("telnet_id",talentId);
        TalentsRepertoryEntity talentsRepertoryEntity = talentsRepertoryDao.selectOne(wrapper);

        if (talentsRepertoryEntity==null || talentsRepertoryEntity.getAdvator() == null){
            return R.ok();
        }

        String advatorPath = talentsRepertoryEntity.getAdvator();

        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(new File(advatorPath));
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok().put("data","data:image/jpeg;base64,"+ Base64.encode(data));
    }






    /*地址信息回显*/
    @GetMapping("/addressOption/{telnetId}")
    public R addressOption(@PathVariable("telnetId")String telnetId){
        ArrayList<String> listData = new ArrayList<>();
        TalentsRepertoryEntity talentsRepertoryEntity = talentsRepertoryService.getById(telnetId);
        if (talentsRepertoryEntity!=null){
            listData.add(talentsRepertoryEntity.getProvinceid());
            listData.add(talentsRepertoryEntity.getCityid());
            listData.add(talentsRepertoryEntity.getAreaid());
        }
        return R.ok().put("data",listData);
    }

    /*行业信息回显*/
    @GetMapping("/optionIndustory/{telnetId}")
    public R optionIndustory(@PathVariable("telnetId")String telnetId){
        ArrayList<String> listData = new ArrayList<>();
        TalentsRepertoryEntity talentsRepertoryEntity = talentsRepertoryService.getById(telnetId);
        if (talentsRepertoryEntity!=null){
            listData.add(talentsRepertoryEntity.getTradeId());
            listData.add(talentsRepertoryEntity.getClassifyId());
            listData.add(talentsRepertoryEntity.getJobTypeId());
        }
        return R.ok().put("data",listData);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("telnets:talentsrepertory:list")
    public R list(@RequestParam Map<String, Object> params){
         R r = talentsRepertoryService.queryPage(params);

        return r;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{telnetId}")
    @RequiresPermissions("telnets:talentsrepertory:info")
    public R info(@PathVariable("telnetId") Long telnetId){
		TalentsRepertoryEntity talentsRepertory = talentsRepertoryService.getById(telnetId);

		QueryWrapper<TelnetEducationBackgroundEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("telnet_id",telnetId);
        List<TelnetEducationBackgroundEntity> telnetEducationBackgroundEntities = telnetEducationBackgroundDao.selectList(wrapper);

        QueryWrapper<WorkTrackRecordEntity> wrapper1 = new QueryWrapper();
        wrapper1.eq("telnet_id",telnetId);
        List<WorkTrackRecordEntity> workTrackRecordEntities = workTrackRecordDao.selectList(wrapper1);


        return R.ok().put("talentsRepertory", talentsRepertory)
                .put("telnetEducationBackgroundEntities",telnetEducationBackgroundEntities)
                .put("workTrackRecordEntities",workTrackRecordEntities);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("telnets:talentsrepertory:save")
    public R save(@RequestBody TalentsRepertoryEntityDTO talentsRepertory){


        TalentsRepertoryEntity telnetEducationBackgroundEntity = new TalentsRepertoryEntity();

        BeanUtils.copyProperties(talentsRepertory,telnetEducationBackgroundEntity);

        /*教育履历*/
        List<TelnetEducationBackgroundEntity> educationList = talentsRepertory.getEducationList();
        /*工作履历*/
        List<WorkTrackRecordEntity> workTrackRecordList = talentsRepertory.getWorkTrackRecordList();


        talentsRepertoryService.save(telnetEducationBackgroundEntity);

        for (TelnetEducationBackgroundEntity itemEducation : educationList){
            itemEducation.setTelnetId(telnetEducationBackgroundEntity.getTelnetId());
            educationBackgroundServicel.save(itemEducation);
        }

        for (WorkTrackRecordEntity itemWork : workTrackRecordList){
            itemWork.setTelnetId(telnetEducationBackgroundEntity.getTelnetId());
            workTrackRecordService.save(itemWork);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @Transactional
    @RequestMapping("/update")
    @RequiresPermissions("telnets:talentsrepertory:update")
    public R update(@RequestBody TalentsRepertoryEntityDTO talentsRepertory){

        TalentsRepertoryEntity talentsRepertoryEntity = new TalentsRepertoryEntity();
        BeanUtils.copyProperties(talentsRepertory,talentsRepertoryEntity);

        List<TelnetEducationBackgroundEntity> educationList = talentsRepertory.getEducationList();
        List<WorkTrackRecordEntity> workTrackRecordList = talentsRepertory.getWorkTrackRecordList();

        //没有记录则执行添加的操作
        if (educationList.size()==0){
            for (TelnetEducationBackgroundEntity itemEdu : educationList){
                itemEdu.setTelnetId(talentsRepertoryEntity.getTelnetId());
                telnetEducationBackgroundDao.insert(itemEdu);
            }
        }else{
            for (TelnetEducationBackgroundEntity itemEdu : educationList){
                TelnetEducationBackgroundEntity telnetEducationBackgroundEntity = telnetEducationBackgroundDao.selectById(itemEdu.getId());
                //执行新增的操作
                if (telnetEducationBackgroundEntity == null){
                    itemEdu.setTelnetId(talentsRepertoryEntity.getTelnetId());
                    telnetEducationBackgroundDao.insert(itemEdu);
                }else{
                    //执行修改的操作
                    itemEdu.setTelnetId(talentsRepertoryEntity.getTelnetId());
                    telnetEducationBackgroundDao.updateById(itemEdu);
                }
            }
        }

        if (workTrackRecordList.size()==0){
            for (WorkTrackRecordEntity itemWork : workTrackRecordList){
                itemWork.setTelnetId(talentsRepertoryEntity.getTelnetId());
                workTrackRecordDao.insert(itemWork);
            }
        }else{
            for (WorkTrackRecordEntity itemWork : workTrackRecordList){
                WorkTrackRecordEntity workTrackRecordEntity = workTrackRecordDao.selectById(itemWork.getId());
                if (workTrackRecordEntity == null){
                    itemWork.setTelnetId(talentsRepertoryEntity.getTelnetId());
                    workTrackRecordDao.insert(itemWork);
                }else{
                    itemWork.setTelnetId(talentsRepertoryEntity.getTelnetId());
                    workTrackRecordDao.updateById(itemWork);
                }
            }
        }

        /*更新人才的基本信息*/
        talentsRepertoryService.updateById(talentsRepertoryEntity);
        return R.ok();
    }

    /**
     * 删除
     */
    @Transactional
    @RequestMapping("/delete")
    @RequiresPermissions("telnets:talentsrepertory:delete")
    public R delete(@RequestBody Long[] telnetIds){

       /*查询出来所有的教育经历并删除掉*/
       QueryWrapper<TelnetEducationBackgroundEntity> wrapper = new QueryWrapper<>();
       wrapper.in("telnet_id",telnetIds);
       List<TelnetEducationBackgroundEntity> telnetEducationBackgroundEntities = telnetEducationBackgroundDao.selectList(wrapper);
       List<Long> eduIds = telnetEducationBackgroundEntities.stream().map(item -> item.getId()).collect(Collectors.toList());
       telnetEducationBackgroundDao.deleteBatchIds(eduIds);

       /*查询出来所有的工作履历并删除掉*/
        QueryWrapper<WorkTrackRecordEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.in("telnet_id",telnetIds);
        List<WorkTrackRecordEntity> workTrackRecordEntities = workTrackRecordDao.selectList(wrapper1);
        List<Long> workIds = workTrackRecordEntities.stream().map(item -> item.getId()).collect(Collectors.toList());
        workTrackRecordDao.deleteBatchIds(workIds);


        /*最后删除人才的基本信息*/
        talentsRepertoryDao.deleteBatchIds(Arrays.asList(telnetIds));

        return R.ok();
    }

}
